package com.lzx.crawler.util;

import com.lzx.crawler.entity.IPEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class CrawlerUtil {
    public static String HEADER_NAME= "user-agent";
    public static String HEADER_VALUE= " Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36";

    public static boolean runTest(IPEntity ip){
        return runTest(ip,"");
    }

    public static boolean runTest(IPEntity ip,String url){
        if(ip == null){
            return false;
        }
        if(url == null || url.equals("")){
            url = "https://www.baidu.com";
        }
        boolean result = false;
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = null;
        try{

            HttpGet get = new HttpGet(url);
            get.setHeader(HEADER_NAME,HEADER_VALUE);
            HttpHost proxy = new HttpHost(ip.getIp(),ip.getPort(),ip.getHeader());
            RequestConfig config = RequestConfig.custom().setProxy(proxy).setConnectTimeout(500).build();
            get.setConfig(config);

            httpClient = HttpClientBuilder.create().build();
            response = httpClient.execute(get);

            if(response.getStatusLine().getStatusCode() == 200) {
                System.out.println("有效！！！");
                result = true;
                EntityUtils.consume(response.getEntity());
            }else{
                EntityUtils.consume(response.getEntity());
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                if(response != null){
                    response.close();
                }
                if(httpClient != null){
                    httpClient.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return result;
    }

}
